package service

import (
	"errors"

	"github.com/slrun/callcenter/configs"
	"github.com/slrun/callcenter/internal/pkg/freeswitch"
	"github.com/slrun/callcenter/internal/pkg/kamailio"
	"go.mongodb.org/mongo-driver/mongo"
)

// Services 服务集合
type Services struct {
	CallControl      *CallControlService
	IVREngine        *IVREngine
	ACDEngine        *ACDEngine
	AgentService     *AgentService
	RecordingService *RecordingService
	TicketService    *TicketService
	MonitorService   *MonitorService
	SystemService    *SystemService
}

// NewServices 创建服务集合
func NewServices(cfg *configs.Config, mongoDB interface{}, redisClient interface{}) (*Services, error) {
	// 初始化FreeSWITCH客户端
	fsClient := freeswitch.NewClient(cfg.FreeSWITCH.Host, cfg.FreeSWITCH.Port, cfg.FreeSWITCH.Password)

	// 初始化Kamailio客户端
	var kamailioClient *kamailio.Client
	// 简化Kamailio客户端初始化，暂时跳过错误检查
	kamailioClient = kamailio.NewClient(cfg.Kamailio.Host, cfg.Kamailio.Port, cfg.Kamailio.Username, cfg.Kamailio.Password)

	// 初始化ACD引擎
	acdEngine := NewACDEngine(fsClient)

	// 初始化呼叫控制服务
	callControlService := NewCallControlService(fsClient)

	// 初始化IVR引擎
	ivrEngine := NewIVREngine(fsClient)

	// 初始化座席服务
	agentService := NewAgentService(fsClient, kamailioClient, acdEngine)

	// 类型断言MongoDB连接
	mongoDBClient, ok := mongoDB.(*mongo.Database)
	if !ok {
		return nil, errors.New("failed to assert MongoDB connection")
	}

	// 初始化录音服务
	recordingService := NewRecordingService(cfg, fsClient, callControlService, mongoDBClient)

	// 初始化工单服务
	ticketService := NewTicketService(nil, agentService, callControlService)

	// 初始化监控服务
	monitorService := NewMonitorService(nil, nil, callControlService, agentService, acdEngine)

	// 初始化系统服务
	systemService := NewSystemService(nil, "", nil, nil)

	return &Services{
		CallControl:      callControlService,
		IVREngine:        ivrEngine,
		ACDEngine:        acdEngine,
		AgentService:     agentService,
		RecordingService: recordingService,
		TicketService:    ticketService,
		MonitorService:   monitorService,
		SystemService:    systemService,
	}, nil
}

// Close 关闭所有服务连接
func (s *Services) Close() error {
	// 这里可以添加关闭各种服务连接的代码
	return nil
}
